
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc,char **argv){
    /*创建套接字相关变量*/
    int client_skt;
    struct sockaddr_in server_addr,client_addr;
    unsigned short portnum=0x8888;
    int addrsize;
    /*辅助变量*/
    int recbyte;
    char buffer[1024]={0};
    /*      */
    printf("Hellp,welcome to my client!\r\n");
    /*创建套接字，用于（connect)*/
    client_skt=socket(AF_INET,SOCK_STREAM,0);
    if(-1==client_skt){
        printf("socket fail!\r\n");
        return -1;
    }
    printf("socker ok!\r\n");
    /*配置服务器IP地址及端口号*/
    bzero(&server_addr,sizeof(struct sockaddr_in));
    server_addr.sin_family=AF_INET;
    server_addr.sin_addr.s_addr=inet_addr(argv[1]);
    server_addr.sin_port=htons(portnum);
    printf("s_addr = %#x,port:%#x\r\n",server_addr.sin_addr.s_addr,server_addr.sin_port);

    /*connect是非阻塞的*/
    if(-1 == connect(client_skt,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))){
        printf("connect fail!\r\n");
        return -1;
    }
    printf("connect ok\r\n");
    while(1){
        /*
        关于read函数：
            是否阻塞，是视设备的属性和设定决定的。
            读字符终端、socket、管道文件，默认值是 阻塞的，读磁盘文件是非阻塞。
        当有一端断开，read的返回值是0
        */
        if(-1==(recbyte = read(client_skt,buffer,1024))||recbyte==0){
            printf("read data fail!\r\n");
            goto END;
        }
        printf("read ok\r\nREC：\r\n");
        buffer[recbyte]='\0';
        printf("%s\r\n",buffer);
        // sleep(10);
        // send(client_skt,buffer,strlen(buffer),0);
    }
END:
    close(client_skt);
    return 0;
}
